<?php

namespace App\Http\Controllers\unicall;

use App\Models\CallRecord\CallRecord;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\unicall\SysConfig;
use App\Http\Controllers\unicall\SysFunction;
use Illuminate\Support\Facades\Redis;

class Index extends Controller
{
    private $sysCon;
    private $function;
    private $appver;
    private $user;
    private $pwd;
    private $account;
    // private $appver;

    function __construct()
    {
        $this->sysCon = new SysConfig();
        $this->function = new SysFunction();

        $this->appver = "1";
        $this->user = env('UNICALL_USER');
        $this->pwd = env('UNICALL_PWD');
        $this->account = env('UNICALL_ACCOUNT');

    }

    /**1
     * 主叫路由添加
     * @param Map parammap中key为主叫号码value为被叫号码
     */
    public function AddCallRouting($parammap)
    {

        $result= $this->function->AddCallRouting($this->appver,$this->user,$this->pwd,$this->account,$parammap);
        return $result;
    }


    /**2
     * 主叫路由清空
     */
    public function  ClearCallRouting(){

        $result= $this->function->ClearCallRouting($this->appver,$this->user,$this->pwd,$this->account);
        return $result;
    }
    /**3
     * 主叫路由删除
     * @param callingid:主叫号码，多个号码英文逗号分隔，上限500个。
     */
    public function  DeleteCallRouting($callingid)
    {
        $result = $this->function->DeleteCallRouting($this->appver,$this->user,$this->pwd,$this->account,$callingid);
        return $result;
    }
    /**4
     * 主叫路由查询
     * @param callingid:主叫号码，多个号码英文逗号分隔，上限500个。
     */
    public function  QueryCallRouting($callingid)
    {

        $result= $this->function->QueryCallRouting($this->appver,$this->user,$this->pwd,$this->account,$callingid);
        return $result;
    }
    /**5
     * 主叫路由数量查询
     */
    public function  QueryCallRoutingSize()
    {
        $result= $this->function->QueryCallRoutingSize($this->appver,$this->user,$this->pwd,$this->account);
        return $result;
    }
    /**6
     * 虚拟分机添加
     * @param Map key存放dn分机编号， value存放tel目的码
     */
    public function  AddExtension($parammap)
    {
        $result= $this->function->AddExtension($this->appver,$this->user,$this->pwd,$this->account,$parammap);
        return $result;
    }
    /**7
     * 虚拟分机批量查询
     * @param pageSize:一页的数量
     * @param pageNow:页编号
     */
    public function  BatchQueryExtension($pageSize,$pageNow)
    {
        $result = $this->function->BatchQueryExtension($this->appver,$this->user,$this->pwd,$this->account,$pageSize,$pageNow);
        return $result;
    }
    /**8
     * 虚拟分机清空
     */
    public function  ClearExtension()
    {
        $result= $this->function->ClearExtension($this->appver,$this->user,$this->pwd,$this->account);
        return $result;
    }
    /**9
     * 虚拟分机删除
     * @param dn 目的码
     */
    public function  DeleteExtension($dn)
    {
        $result= $this->function->DeleteExtension($this->appver,$this->user,$this->pwd,$this->account,$dn);
        return $result;
    }
    /**10
     * 虚拟分机查询
     * @param dn 目的吗
     */
    public function  QueryExtension($dn)
    {
        $result= $this->function->QueryExtension($this->appver,$this->user,$this->pwd,$this->account,$dn);
        return $result;
    }
    /**11
     * 隐号添加
     * @param Map key存放phone， value存放phone
     */
    public function  AddHiddedPhone($parammap)
    {
        $result= $this->function->AddHiddedPhone($this->appver,$this->user,$this->pwd,$this->account,$parammap);
        return $result;
    }
    /**12
     * 隐号清空
     */
    public function  ClearHiddedPhone()
    {
        $result= $this->function->ClearHiddedPhone($this->appver,$this->user,$this->pwd,$this->account);
        return $result;
    }
    /**13
     * 隐号删除
     * @param phone1:号码，多个号码则英文逗号分隔，上限500个。
     */
    public function  DeleteHiddedPhone($phone1)
    {
        $result= $this->function->DeleteHiddedPhone($this->appver,$this->user,$this->pwd,$this->account,$phone1);
        return $result;
    }
    /**14
     * 隐号查询
     * @param phone1:号码，多个号码则英文逗号分隔，上限500个。
     */
    public function  QueryHiddedPhone($phone1)
    {
        $result= $this->function->QueryHiddedPhone($this->appver,$this->user,$this->pwd,$this->account,$phone1);
        return $result;
    }
    /**15
     * 隐号数量查询
     */
    public function  QueryHiddedPhoneSize()
    {
        $result= $this->function->QueryHiddedPhoneSize($this->appver,$this->user,$this->pwd,$this->account);
        return $result;
    }
    /**16
     * 黑名单添加
     * @param phone 号码，多个号码则英文逗号分隔，上限500个
     */
    public function  AddBlackList($phone)
    {
        $result= $this->function->AddBlackList($this->appver, $this->user, $this->pwd, $this->account, $phone);
        return $result;
    }
    /**17
     * 黑名单清空
     */
    public function   ClearBlackList()
    {
        $result= $this->function->ClearBlackList($this->appver,$this->user,$this->pwd,$this->account);
        return $result;
    }
    /**18
     *黑名单删除
     * @param phone 号码，多个号码则英文逗号分隔，上限500个
     */
    public function  DeleteBlackList($phone)
    {
        $result= $this->function->DeleteBlackList($this->appver, $this->user, $this->pwd, $this->account, $phone);
        return $result;
    }
    /**19
     * 黑名单查询
     */
    public function  QueryBlackList()
    {
        $result= $this->function->QueryBlackList($this->appver,$this->user,$this->pwd,$this->account);
        return $result;
    }
    /**20
     *动态目标码删除
     *  @param transferid:转接节点ID
     */
    public function  DeleteDynaDestNum($transferid)
    {
        $result= $this->function->DeleteDynaDestNum($this->appver, $this->user, $this->pwd, $this->account, $transferid);
        return $result;
    }
    /**21
     *动态目标码查询
     *  @param transferid:转接节点ID
     */
    public function  QueryDynaDestNum($transferid)
    {
        $result= $this->function->QueryDynaDestNum($this->appver, $this->user, $this->pwd, $this->account, $transferid);
        return $result;
    }
    /**22
     *动态目标码更新
     * @param transferid:转接节点ID
     * @param destNum:目标号码，多个号码英文逗号分隔，例如：134104456433,13433233443
     */
    public function  UpdateDynaDestNum($transferid,$destNum)
    {
        $result= $this->function->UpdateDynaDestNum($this->appver, $this->user, $this->pwd, $this->account, $transferid,$destNum);
        return $result;
    }
    /**23
     * 呼叫事件提取
     */
    public function QueryCallEvent()
    {
        $result= $this->function->QueryCallEvent($this->appver,$this->user,$this->pwd,$this->account);
        return $result;
    }
    /**24
     * 点击呼叫结果查询
     */
    public function QueryClickCall()
    {
        $result= $this->function->QueryClickCall($this->appver,$this->user,$this->pwd,$this->account);
        return $result;
    }
    /**25
     * 点击呼叫申请
     * callingid:主叫号码
     * calledid:被叫号码
     */
    public function RequestClickCall($callingid,$calledid)
    {
        $result= $this->function->RequestClickCall($this->appver,$this->user,$this->pwd,$this->account,$callingid,$calledid);
        return $result;
    }
    /**26
     * 通话记录查询
     * @param startTime:通话记录创建的开始时间，格式：yyyyMMddHHmmss，开始和结束时间必须是同一月份，不支持跨月查询。
     * @param endTime:通话记录创建的结束时间，格式：yyyyMMddHHmmss，开始和结束时间必须是同一月份，不支持跨月查询。
     * @param pageSize:一页的通话数量，最大500
     * @param pageNow:页编号，从1开始
     */
    public function QueryCallRecord(Request $request)
    {
//        return $this->downVioce('http://123.56.44.174:51580/record/RemoteRecord/record/2018/11/14/4006512407_4006512407_01064528902_17fc21a637b886f106755877283c582d@47.92.27.40_20181114154604.wav');
        return $this->_QueryCallRecord();
    }

    /**
     * 递归查询通话记录并保存至数据库（每次添加100条数据，每个凌晨12点执行）
     * @param int $pageNow
     * @param string $result
     * @return mixed|string
     */
    public function _QueryCallRecord(&$pageNow = 1, &$result = '{}')
    {
        $startTime = date('Ymd'.'000000', strtotime('-1 day'));
        $endTime = date('Ymd'.'000000');
        $pageSize = 100;
        $token = $this->getToken();
        $result= $this->function->QueryCallRecord($this->appver, $this->user, $token, $this->account, $startTime, $endTime, $pageSize, $pageNow);
        $obj = json_decode($result);

        if ($obj->errcode == 0) {
            if ($obj->data->rows) {
                $rows = $obj->data->rows;
                foreach ($rows as $v) {
                    $data = [];
                    foreach ($v as $k => $vv) {
                        $data[$k] = $vv;
                    }

                    //判断数据库是否已存在该记录
                    $res = CallRecord::where('serviceSn', '=', $data['serviceSn'])->first();
                    if(!$res){
                        $url = $this->downVioce($data['recordUrl']);
                        $data['localRecordUrl'] = $url;
                        CallRecord::insert($data);
                    }
                }
                $pageNow ++;
                $this->_QueryCallRecord($pageNow, $result);
            }else{
                return $result;
            }
        }
        return $result;
    }

    /**
     * 将远程音频文件保存至本地
     * @param $url
     * @return bool|int
     */
    public function downVioce($url)
    {
        $vioce = file_get_contents($url);
        $filename = './callRecord/'.pathinfo($url)['basename'];
        if (!file_exists($filename)) {
            $res = file_put_contents($filename, $vioce);
            if (!$res)
                return auto_failure('录音文件保存失败');
        }
        return '/callRecord/'.pathinfo($url)['basename'];
    }

    /**27
     * 满意度记录查询
     * @param startTime:通话记录创建的开始时间，格式：yyyyMMddHHmmss，开始和结束时间必须是同一月份，不支持跨月查询。
     * @param endTime:通话记录创建的结束时间，格式：yyyyMMddHHmmss，开始和结束时间必须是同一月份，不支持跨月查询。
     * @param pageSize:一页的通话数量，最大500
     * @param pageNow:页编号，从1开始
     */
    public function  QuerySatisfaction($startTime,$endTime,$pageSize,$pageNow)
    {
        $result= $this->function->QuerySatisfaction($this->appver, $this->user, $this->pwd, $this->account, $startTime, $endTime, $pageSize, $pageNow);
        return $result;
    }
    /**28
     *	短信报告查询
     * @param serviceSn 短信流水号，如果不填，则返回有运营商报告的短信记录，上限500条。
     */
    public function QuerySmsReport($serviceSn)
    {
        $result= $this->function->QuerySmsReport($this->appver, $this->user, $this->pwd, $this->account, $serviceSn);
        return $result;
    }
    /**29
     *	短信发送
     * @param List: 发送的短信内容，JSONArray格式，数量和模板中变量个数匹配。示例：短信模板为：您的验证码为{1},客服电话{2}
     * 				data：["123567","13810443533"]平台会自动和模板匹配，生成短信：您的验证码123567,客服电话13810443533。
     * @param:	mobile接收短信的手机号码多个手机号码，英文逗号分隔，上限100个。
     * @param:templateId模板编号客户提供短信模板到信通工作人员，工作人员在管理平台审核通过后，提供给客户该编号。
     */
    public function  RequestSmsSend($paramlist,$mobile,$templateId)
    {
        $result= $this->function->RequestSmsSend($this->appver, $this->user, $this->pwd, $this->account, $paramlist, $mobile, $templateId);
        return $result;
    }
    /**30
     * 网页呼叫结果提取
     */
    public function  QueryWebcall()
    {
        $result= $this->function->QueryWebcall($this->appver,$this->user,$this->pwd,$this->account);
        return $result;
    }
    /**31
     * 网页呼叫申请
     * @param callingid:主叫号码，手机号码或者固话号码，手机号码格式:18611334885, 不需要添加0或者区号。固话格式：01053358846，不需要添加任何其它非数字内容。
     */
    public function RequestWebCall($callingid)
    {
        $result= $this->function->RequestWebcall($this->appver,$this->user,$this->pwd,$this->account,$callingid);
        return $result;
    }

    /**32
     * 语音验证码结果查询
     *
     */
    public function  VoiceResultSearch()
    {
        $result= $this->function->VoiceResultSearch($this->appver,$this->user,$this->pwd,$this->account);
        return $result;
    }
    /** 33
     * 语音验证码申请
     * @param dnis:被叫号码
     * @param voicecode:语音验证码
     */
    public function VoiceVerification($dnis,$voicecode)
    {
        $result= $this->function->voice($this->appver,$this->user,$this->pwd,$this->account,$dnis,$voicecode);
        return $result;
    }

    public function getToken()
    {
        $token = Redis::get('uni_token');
        if($token)
            return $token;
        $result = $this->function->login($this->appver, $this->user, $this->pwd);
        if (""== $result  || "1"== $result || $result==null) {
            return auto_failure('获取token失败');
        }else{
            Redis::set('uni_token', $result);
            Redis::expire('uni_token', 82800);
            return $result;
        }
    }

}
